package com.eqdd.yiqidian.ui.mine.shenqing;

import android.Manifest;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bigkoo.pickerview.TimePickerView;
import com.coorchice.library.SuperTextView;
import com.eqdd.yiqidian.CreateNoticeActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.RecyclerViewCustom;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseApplication;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.MemoResultBean;
import com.eqdd.yiqidian.bean.rebuild.SearchPersonResultBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimAddEditBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditCheckButtonBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditChooseBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditEnterBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditTimeBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimTwoSectionEditBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.ui.base.SlimBaseMultiEditActivity;
import com.eqdd.yiqidian.utils.CalendarEventUtil;
import com.eqdd.yiqidian.utils.DateUtil;
import com.eqdd.yiqidian.utils.IntentUtil;
import com.eqdd.yiqidian.utils.PermissionTipUtil;
import com.eqdd.yiqidian.utils.SPUtil;
import com.eqdd.yiqidian.utils.SingleChooseUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.ActionSheetDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class CreateMemoActivity extends SlimBaseMultiEditActivity {
    private RecyclerViewCustom dataBinding;
    private ActionSheetDialog chooseDialogRelate;
    private String msg;
    private int clickPos;
    private boolean isUpper;
    private boolean isYear;
    private MemoResultBean memoResultBean;
    private MaterialDialog build;

    @Override
    public void initBinding() {
        memoResultBean = (MemoResultBean) getIntent().getSerializableExtra("bean");
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_recyclerview);
        if (memoResultBean != null) {
            isRead = false;
            isSave = false;
            initTopTitleBar(View.VISIBLE, "事件详情");
            initTopRightText("删除", v -> {
                OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.DELETE_MEMO)
                        .params("memoid", memoResultBean.getId())
                        .execute(new DialogCallBack<HttpResult>(this) {
                            @Override
                            public void onSuccess(Response<HttpResult> response) {
                                HttpResult httpResult = response.body();
                                ToastUtil.showShort(httpResult.getMsg());
                                if (httpResult.getStatus() == 200) {
                                    setResult(Config.DELETE);
                                    finish();
                                }
                            }
                        });

            });
        } else {
            initTopTitleBar(View.VISIBLE, "新建备忘录");
            initTopRightText("创建", v -> {
                if (checkParam()) {
                    SlimTwoSectionEditBean dataItem1 = (SlimTwoSectionEditBean) slimAdapterEx.getDataItem(1);
                    SlimTwoSectionEditBean dataItem2 = (SlimTwoSectionEditBean) slimAdapterEx.getDataItem(2);
                    RxPermissions.getInstance(CreateMemoActivity.this).request(Manifest.permission.READ_CALENDAR,
                            Manifest.permission.WRITE_CALENDAR)
                            .subscribe(granted -> {
                                if (granted) {
                                    System.out.println("授权成功");
                                    String s = dataItem1.getUpContent() + " " + dataItem2.getUpContent();
                                    String e = dataItem1.getDownContent() + " " + dataItem2.getDownContent();
                                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                                    Date startdate = null;
                                    Date enddate = null;
                                    try {
                                        startdate = sf.parse(s);
                                        enddate = sf.parse(e);
                                    } catch (ParseException e1) {
                                        e1.printStackTrace();
                                    }
                                    boolean isEventOk = CalendarEventUtil.addCalendarEvent(AppConstent.user.getPname(), setParam(0), setParam(4)
                                            , setParam(6), startdate.getTime(), enddate.getTime(), Integer.parseInt(setParam(3).replace("分钟", "")));
                                    if (!isEventOk) {
                                        ToastUtil.showShort("本地日历事件添加失败");
                                    }
                                    OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.CREATE_MEMO)
                                            .params("userGuid", user.getGuid())
                                            .params("eventName", setParam(0))
                                            .params("startDate", dataItem1.getUpContent())
                                            .params("endDate", dataItem1.getDownContent())
                                            .params("startTime", dataItem2.getUpContent())
                                            .params("endTime", dataItem2.getDownContent())
                                            .params("timeToRemind", setParam(3).replace("分钟", ""))
                                            .params("memoInfo", setParam(4))
                                            .params("eventType", setParam(5))
                                            .params("place", setParam(6))
                                            .execute(new DialogCallBack<HttpResult>(this) {
                                                @Override
                                                public void onSuccess(Response<HttpResult> response) {
                                                    HttpResult httpResult = response.body();
                                                    if (httpResult.getStatus() == 200) {
                                                        clearData();
                                                        setResult(Config.SUCCESS);
                                                        finish();
                                                    }
                                                }
                                            });

                                } else {
                                    PermissionTipUtil.tip(CreateMemoActivity.this, "日历");

                                }

                            });

                } else {

                    ToastUtil.showShort(msg);
                }
            });
        }
    }

    private boolean checkParam() {
        if (TextUtils.isEmpty(datas.get(0).getContent())) {
            msg = "请输入事件名称";
            return false;
        }
        SlimTwoSectionEditBean dataItem = (SlimTwoSectionEditBean) slimAdapterEx.getDataItem(1);
        if (TextUtils.isEmpty(dataItem.getUpContent()) || TextUtils.isEmpty(dataItem.getDownContent())) {
            msg = "日期时间不完整";
            return false;
        }
        dataItem = (SlimTwoSectionEditBean) slimAdapterEx.getDataItem(2);
        if (TextUtils.isEmpty(dataItem.getUpContent()) || TextUtils.isEmpty(dataItem.getDownContent())) {
            msg = "时分时间不完整";
            return false;
        }
        if (TextUtils.isEmpty(datas.get(3).getContent())) {
            msg = "请选择提醒时间";
            return false;
        }
        if (TextUtils.isEmpty(datas.get(4).getContent())) {
            msg = "请输入事件内容";
            return false;
        }
        if (TextUtils.isEmpty(datas.get(5).getContent())) {
            msg = "请选择事件类型";
            return false;
        }
        return true;
    }


    @Override
    protected RecyclerView initRecyclerView() {
        return dataBinding.recyclerView;
    }

    @Override
    public void itemClick(int p) {
        switch (slimAdapterEx.getDataItem(p).getPosition()) {
//            case 5:
//                if (chooseDialogRelate == null) {
//                    SingleChooseUtil.getChooseDialog(CreateMemoActivity.this, 28, (sheet) -> {
//                        chooseDialogRelate = sheet;
//                        sheet.show();
//                    }, (position, strings) -> {
//                        slimAdapterEx.getDataItem(p).setContent(strings.get(position - 1));
//                        slimAdapterEx.notifyItemChanged(p);
//                        updateMemo();
//                    });
//                } else {
//                    chooseDialogRelate.show();
//                }
//                break;
        }
    }

    @Override
    protected void onChooseClick(int position) {
        if (memoResultBean != null) {
            updateMemo();
        }
    }

    private void updateMemo() {
        if (memoResultBean != null) {
            SlimTwoSectionEditBean dataItem1 = (SlimTwoSectionEditBean) slimAdapterEx.getDataItem(1);
            SlimTwoSectionEditBean dataItem2 = (SlimTwoSectionEditBean) slimAdapterEx.getDataItem(2);
            OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.UPDATE_MEMO)
                    .params("memoid", memoResultBean.getId())
                    .params("userGuid", user.getGuid())
                    .params("eventName", setParam(0))
                    .params("startDate", dataItem1.getUpContent())
                    .params("endDate", dataItem1.getDownContent())
                    .params("startTime", dataItem2.getUpContent())
                    .params("endTime", dataItem2.getDownContent())
                    .params("timeToRemind", setParam(3).replace("分钟", ""))
                    .params("memoInfo", setParam(4))
                    .params("eventType", setParam(5))
                    .params("place", setParam(6))
                    .execute(new DialogCallBack<HttpResult>(CreateMemoActivity.this) {
                        @Override
                        public void onSuccess(Response<HttpResult> response) {
                            HttpResult httpResult = response.body();
                            ToastUtil.showShort(httpResult.getMsg());
                            if (httpResult.getStatus() == 200) {

                                setResult(Config.SUCCESS);
                            }
                        }
                    });
        }
    }

    @Override
    protected void setEditBeans() {
        String[] s = new String[]{
                "10分钟",
                "30分钟",
                "60分钟",
                "90分钟"
        };
        String content = getIntent().getStringExtra(Config.CONTENT);

        if (content != null && !"".equals(content)) {
            isSave = false;
            isRead = false;
        }

        datas.add(new SlimEditEnterBean("事件名称", memoResultBean == null ? "" : memoResultBean.getEventName(), 0, "请输入事件名称"));
        datas.add(new SlimTwoSectionEditBean("", "", 1, "开始日期", "结束日期", memoResultBean == null ? "" : DateUtil.format(memoResultBean.getStartDate(), "yyyy-MM-dd"), memoResultBean == null ? "" : DateUtil.format(memoResultBean.getEndDate(), "yyyy-MM-dd")));
        datas.add(new SlimTwoSectionEditBean("", "", 2, "开始时分", "结束时分", memoResultBean == null ? "" : memoResultBean.getStartTime().substring(0, 5), memoResultBean == null ? "" : memoResultBean.getEndTime().substring(0, 5)));
        datas.add(new SlimEditChooseBean("提醒时间", memoResultBean == null ? "" : memoResultBean.getTimeToRemind() + "分钟", 3, "请选择", s));
        datas.add(new SlimEditEnterBean("内容", content == null ? (memoResultBean == null ? "" : memoResultBean.getMemoInfo()) : content, 4, "请输入事件内容"));
        datas.add(new SlimEditChooseBean("类型", memoResultBean == null ? "" : memoResultBean.getEventType(), 5, "请选择事件类型", new String[]{"空闲", "暂定", "忙碌", "外出"}));
        datas.add(new SlimEditEnterBean("位置", memoResultBean == null ? "" : memoResultBean.getPlace(), 6, "请输入位置"));
        slimAdapterEx.register(R.layout.list_item_42, new SlimInjector<SlimTwoSectionEditBean>() {
            @Override
            public void onInject(SlimTwoSectionEditBean data, IViewInjector injector) {
                injector.text(R.id.tv_upper_left_content, data.getUpTitle())
                        .text(R.id.tv_upper_right_content, data.getUpContent())
                        .text(R.id.tv_down_left_content, data.getDownTitle())
                        .text(R.id.tv_down_right_content, data.getDownContent())
                        .gone(R.id.stv_bottom)
                        .with(R.id.tv_upper_right_content, v -> ((TextView) v).setHint("请选择"))
                        .with(R.id.tv_down_right_content, v -> ((TextView) v).setHint("请选择"))
                        .clicked(R.id.rl_upper, v -> {
                            isYear = slimAdapterEx.getData().indexOf(data) == 1;
                            clickPos = slimAdapterEx.getData().indexOf(data);
                            isUpper = true;
                            openTimePicker();
                        })
                        .clicked(R.id.rl_down, v -> {
                            isYear = slimAdapterEx.getData().indexOf(data) == 1;
                            clickPos = slimAdapterEx.getData().indexOf(data);
                            isUpper = false;
                            openTimePicker();
                        });

            }
        });

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.INTENT_CONTENT) {
            updateMemo();
        }
    }

    private void openTimePicker() {
        Calendar now = Calendar.getInstance();
        now.setTime(new Date());
        TimePickerView pvDayTime = new TimePickerView.Builder(this, (date, v) -> {

            SlimTwoSectionEditBean dataItem = (SlimTwoSectionEditBean) slimAdapterEx.getDataItem(clickPos);
            String parse;
            if (isYear) {
                parse = DateUtil.parse(date, "yyyy-MM-dd");
            } else {
                parse = DateUtil.parse(date, "HH:mm");
            }
            if (isUpper) {
                dataItem.setUpContent(parse);
                slimAdapterEx.notifyItemChanged(clickPos);
                updateMemo();
            } else {
                dataItem.setDownContent(parse);
                slimAdapterEx.notifyItemChanged(clickPos);
                updateMemo();
            }
        })
                .setOutSideCancelable(true)
                .setType(isYear ? Config.YEAR_MONTH_DAY_TYPE : Config.HOUR_MINITE_TYPE)
                .setRange(now.get(Calendar.YEAR), 2050)
                .setDate(now)
                .build();
        pvDayTime.show();
    }

}
